package org.zuel.boot.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.var;
import org.springframework.stereotype.Service;
import org.zuel.boot.demo.entity.StudentResume;
import org.zuel.boot.demo.entity.SysUser;
import org.zuel.boot.demo.exception.ParameterException;
import org.zuel.boot.demo.mapper.StudentResumeMapper;
import org.zuel.boot.demo.service.IStudentResumeService;
import org.zuel.boot.demo.web.JsonResult;
import org.zuel.boot.demo.web.PageParam;
import org.zuel.boot.demo.web.PageResult;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 *  服务实现类
 *
 * @author ikun
 */
@Service
public class StudentResumeServiceImpl extends ServiceImpl<StudentResumeMapper, StudentResume> implements IStudentResumeService {

    @Override
    public PageResult<StudentResume> list(PageParam<StudentResume> page) {
        return new PageResult<>(this.page(page).getRecords(), page.getTotal());
    }

    // AI 接口调用方法
    @Override
    public JsonResult read(SysUser user) {
        QueryWrapper<StudentResume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", user.getUserId());
        StudentResume existingResume = baseMapper.selectOne(queryWrapper);

        if (existingResume != null) {
            // 汇总简历内容
            String resumeContent = "爱好特长: " + existingResume.getAhtc() + " " +
                    "个人技能: " + existingResume.getGrjn() + " " +
                    "社会实践经历及任职情况: " + existingResume.getShsjjljrzqk() + " " +
                    "获奖及发表作品情况: " + existingResume.getHjjfbzpqk() + " " +
                    "主要科研活动和学术活动: " + existingResume.getZykyhdhxshd() + " " +
                    "个人自荐和求职意向: " + existingResume.getGrzjhqzyx() + " "
            ;
            // 调用 AI 接口获取分析结果
            String aiAnalysisResult = simpleMultiModalConversationCall(resumeContent);

            // 将 AI 分析结果设置到 StudentResume 对象中
            existingResume.setAiAnalysis(aiAnalysisResult);
        }
        return JsonResult.ok().setData(existingResume);
    }
    private String simpleMultiModalConversationCall(String text) {
        try {
            // 创建对话对象
            MultiModalConversation conv = new MultiModalConversation();

            // 构建系统消息
            MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                    .content(Collections.singletonList(
                            Collections.singletonMap("text", "You are a helpful assistant."))).build();

            // 构建用户消息
            MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                    .content(Arrays.asList(
                            Collections.singletonMap("text", text),
                            Collections.singletonMap("text", "你是一位HR，这是一个用户的个人简历信息，请你分析其适合的就业岗位,只需要给出岗位即可,并且岗位也可以继续细化到从事哪些行业的岗位"))).build();

            // 构建请求参数
            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    .apiKey(System.getenv("sk-5019fa9093804345a57078be7b9d3031"))
                    .model("qwen-vl-max-latest")
                    .messages(Arrays.asList(systemMessage, userMessage))
                    .build();

            // 调用接口
            MultiModalConversationResult result = conv.call(param);

            // 检查返回结果
            if (result.getOutput() != null && result.getOutput().getChoices() != null && !result.getOutput().getChoices().isEmpty()) {
                var choice = result.getOutput().getChoices().get(0);
                if (choice.getMessage() != null && choice.getMessage().getContent() != null && !choice.getMessage().getContent().isEmpty()) {
                    // 直接获取并返回文本内容，移除换行符
                    return choice.getMessage().getContent().get(0).get("text").toString().replace("\n", " ");
                }
            }

            // 如果结果无效，返回默认错误提示
            return "未获取到有效的响应结果。";

        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            // 捕获异常并返回错误信息
            return "调用 AI 服务时发生错误: " + e.getMessage();
        }
    }
    @Override
    public JsonResult add(StudentResume StudentResume) {
        if (StudentResume ==null){
            throw new ParameterException("参数对象为空");
        }

        baseMapper.insert(StudentResume);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult update(StudentResume studentResume, SysUser user) {
        if (studentResume == null) {
            throw new ParameterException("参数对象为空");
        }
        studentResume.setStudentId(user.getUserId());
        QueryWrapper<StudentResume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", user.getUserId());
        StudentResume existingResume = baseMapper.selectOne(queryWrapper);
        if (existingResume != null) {
            baseMapper.updateById(studentResume);
        }else{
            // 如果不存在简历记录，插入新记录
            int insertResult = baseMapper.insert(studentResume);
            if (insertResult <= 0) {
                throw new ParameterException("插入简历失败");
            }
        }
        return JsonResult.ok("成功");
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null) {
            throw new ParameterException("参数对象为空");
        }

        if (ids != null || ids.length > 0) {
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }

}